package cn.tedu.zhxy.controller;

import cn.tedu.zhxy.dto.LoginDTO;
import cn.tedu.zhxy.entity.Admin;
import cn.tedu.zhxy.entity.Student;
import cn.tedu.zhxy.entity.Teacher;
import cn.tedu.zhxy.service.AdminService;
import cn.tedu.zhxy.service.StudentService;
import cn.tedu.zhxy.service.TeacherService;
import cn.tedu.zhxy.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private  AdminService  adminService;

    @Autowired
    private StudentService  studentService;

    @Autowired
    private TeacherService teacherService;

    @GetMapping("updatePwd/{oldPwd}/{newPwd}")
    public   Result  updatePwd(@RequestHeader("token") String  token,@PathVariable("oldpwd") String   oldPwd,
                               @PathVariable("newPwd") String  newPwd){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration ) {
            return  Result.fail().message("token失效，请重新登录");
        }
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        String oldPwd1 = MD5.encrypt(oldPwd);
        String newPwd1 = MD5.encrypt(newPwd);

        switch (userType){
            case 1:
                QueryWrapper  queryWrapper = new QueryWrapper();
                queryWrapper.eq("id",userId.intValue());
                queryWrapper.eq("password",oldPwd1);
                Admin admin = adminService.getOne(queryWrapper);
                if (admin!=null){
                    admin.setPassword(newPwd1);
                    adminService.saveOrUpdate(admin);
                }else{
                    return Result.fail().message("原密码错误");
                }
                break;
            case 2:
                QueryWrapper  queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("id",userId.intValue());
                queryWrapper1.eq("password",oldPwd1);
                Student  student = studentService.getOne(queryWrapper1);
                if (student!=null){
                    student.setPassword(newPwd1);
                    studentService.saveOrUpdate(student);
                }else{
                    return Result.fail().message("原密码错误");
                }
                break;
            case 3:
                QueryWrapper  queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("id",userId.intValue());
                queryWrapper2.eq("password",oldPwd1);
               Teacher teacher= teacherService.getOne(queryWrapper2);
                if (teacher!=null){
                    teacher.setPassword(newPwd1);
                    teacherService.saveOrUpdate(teacher);
                }else{
                    return Result.fail().message("原密码错误");
                }
        }

        return  Result.ok();
    }

    @PostMapping("headerImgUpload")
    public Result  upLoadImage(@RequestPart("multipartFile") MultipartFile  multipartFile){
        String originalFilename = multipartFile.getOriginalFilename();
        //得到后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String  fileName = UUID.randomUUID()+suffix;
        String  dirPath = "E:/ideaworkspace/zhxy/target/classes/public/upload";
        File  dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        //完整的文件路径
        String  newFile = dirPath+"/"+fileName;
        try {
            multipartFile.transferTo(new File(newFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  Result.ok("upload/"+fileName);
    }

    //带着token请求访问返回人员信息
    @GetMapping("getInfo")
    public  Result  info(@RequestHeader("token") String  token){
        //检查token是不是过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        Integer userType = JwtHelper.getUserType(token);
        Long userId = JwtHelper.getUserId(token);
        System.out.println("userId"+userId);
        Map<String,  Object>  map = new HashMap<>();
        switch (userType){
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
               Student  student = studentService.getById(userId);
                System.out.println("xueyuan "+student);
                map.put("userType",2);
                map.put("user",student);
                break;
            case  3:
                Teacher  teacher = teacherService.getById(userId);
                map.put("userType",3);
                map.put("user",teacher);
        }

        return   Result.ok(map);
    }
    @PostMapping("login")
    public Result login(@RequestBody LoginDTO loginDTO, HttpServletRequest  session){

        //校验验证码
        System.out.println(loginDTO);
        String sessionVerifiCode = (String) session.getSession().getAttribute("verifiCode");
        String verifiCode = loginDTO.getVerifiCode();
        System.out.println(sessionVerifiCode+"..."+verifiCode);
        if (verifiCode == null||"".equals(verifiCode)) {
            return  Result.fail().message("验证码失效，请刷新后重试");
        }
        if (!verifiCode.equals(sessionVerifiCode)) {
            return  Result.fail().message("验证码有误，请刷新后重试");
        }
        //校验完之后移除session
        session.removeAttribute("verifiCode");
        //用户分类校验
        Map map = new HashMap();
         switch (Integer.valueOf(loginDTO.getUserType())){
             case 1:
                 try {
                     Admin admin = adminService.login(loginDTO);
                     if (admin!=null){
                         //如果存在，将用户的类型和id转换成密文，以tocken的方式相应前端
                         String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                         map.put("token",token);
                     }else{
                         throw new RuntimeException("用户名或者密码有误，请重新输入");
                     }

                     return Result.ok(map);
                 } catch (Exception e) {
                     e.printStackTrace();
                     return   Result.fail().message(e.getMessage());
                 }
             case 2:
                 try {
                     Student student = studentService.login(loginDTO);
                     if (student!=null){
                         //如果存在，将用户的类型和id转换成密文，以tocken的方式相应前端
                         String token = JwtHelper.createToken(student.getId().longValue(), 2);
                         map.put("token",token);
                     }else{
                         throw new RuntimeException("用户名或者密码有误，请重新输入");
                     }
                     return Result.ok(map);
                 } catch (Exception e) {
                     e.printStackTrace();
                     return   Result.fail().message(e.getMessage());
                 }
             case 3:
                 try {
                 Teacher teacher = teacherService.login(loginDTO);
                 if (teacher!=null){
                     //如果存在，将用户的类型和id转换成密文，以tocken的方式相应前端
                     String token = JwtHelper.createToken(teacher.getId().longValue(), 3);
                     map.put("token",token);
                 }else{
                     throw new RuntimeException("用户名或者密码有误，请重新输入");
                 }
                 return Result.ok(map);
             } catch (Exception e) {
                 e.printStackTrace();
                 return   Result.fail().message(e.getMessage());
             }

         }
         return Result.fail().message("查无此用户");
    }

    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        // 获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取图片上的验证码
        String verifiCode =new String( CreateVerifiCodeImage.getVerifiCode());
        // 将验证码文本放入session域,为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        // 将验证码图片响应给浏览器

        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
